package com.lighting.smssystem.utils.mybatis;

import com.lighting.smssystem.constrants.UserStatus;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Author LeeMaster
 */
public class UserStatusTypeHandler extends BaseTypeHandler<UserStatus> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, UserStatus parameter, JdbcType jdbcType) throws SQLException {
        if (parameter != null){
            ps.setInt(i,parameter.code);
        }else {
            ps.setInt(i,UserStatus.AVAILABLE.code);
        }
    }

    @Override
    public UserStatus getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return getStatus(rs.getInt(columnName));
    }

    @Override
    public UserStatus getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return getStatus(rs.getInt(columnIndex));
    }

    @Override
    public UserStatus getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return getStatus(cs.getInt(columnIndex));
    }

    private UserStatus getStatus(int code){
        switch (code){
            case 1:
                return UserStatus.FORBIDDEN;
                default:
                    return UserStatus.AVAILABLE;
        }
    }
}
